<template>
    <div>
        <el-main>
            <div class="box">
                <div class="top">
                    <el-form :inline="true" :model="queryForm" class="demo-form-inline" label-suffix=":" size="medium">
                        <el-form-item label="时间(年-月)">
                            <el-date-picker v-model="queryForm.yearMonth" type="month" format="yyyy-MM"
                                style="width: 140px;" @change="onDateChange" :clearable="false" />
                        </el-form-item>
                        <el-form-item label="数据状态">
                            <el-select v-model="queryForm.selectedStatus" @change="handSelectState"
                                style="width: 140px;">
                                <el-option value="all" label="全部"></el-option>
                                <el-option value="wtj" label="未提交"></el-option>
                                <el-option value="101" label="待审核"></el-option>
                                <el-option value="103" label="审核未通过"></el-option>
                                <el-option value="shtg" label="审核通过"></el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="断面名称">
                            <el-input v-model="queryForm.keyword" style="width: 140px;" placeholder="输入关键字"
                                @input="handInput" />
                        </el-form-item>
                        <el-form-item>
                            <el-button type="primary" @click="handleOneKeyAudit">一键审核</el-button>
                            <el-button type="danger" @click="handleOneKeyRollback">一键回退</el-button>
                            <el-button type="success" @click="handleDataExport">数据导出</el-button>
                        </el-form-item>
                    </el-form>
                    <div style="
              float: right;
              margin-right: 60px;
              display: flex;
              align-items: center;
            "></div>
                </div>
                <div class="center">
                    <el-table :data="paginatedData" border style="width: 100%" size="medium" :max-height="tableheight"
                        @selection-change="handleSelectionChange">
                        <el-table-column type="selection" width="55"></el-table-column>
                        <el-table-column prop="dmmc" label="断面名称" show-overflow-tooltip />
                        <el-table-column prop="liuyu" label="所在流域" show-overflow-tooltip />

                        <el-table-column prop="xzqhname" label="行政区划" show-overflow-tooltip />
                        <el-table-column prop="szmb" label="水质目标" show-overflow-tooltip />
                        <el-table-column prop="szlb" label="水质类别" show-overflow-tooltip>
                            <template slot-scope="scope">
                                <!-- <span>{{ scope.row.szlb && scope.row.szlb != 0 ? config.typeArray.find(item =>
                                    item.value ==
                                    scope.row.szlb).label : '未监测' }}</span> -->
                                <span>{{ getType(scope.row.szlb) }}</span>
                            </template>
                        </el-table-column>
                        <el-table-column prop="dmlaiyuan" label="断面类型" show-overflow-tooltip />

                        <el-table-column prop="shenhezt" label="数据状态">
                            <template slot-scope="scope">
                                <el-tag :type="config.shenhezt[scope.row.shenhezt].color" size="small">
                                    {{ config.shenhezt[scope.row.shenhezt].status }}
                                </el-tag>
                            </template>
                        </el-table-column>

                        <el-table-column prop="action" label="操作" width="170" align="center">
                            <template slot-scope="scope">
                                <!-- 根据状态显示不同的按钮 -->
                                <!-- 根据状态显示不同的按钮 -->
                                <el-button v-if="scope.row.shenhezt === '00'" :key="'a' + scope.$index"
                                    :type="config.shenhezt['00'].color" size="mini" disabled>
                                    审核
                                </el-button>
                                <el-button v-else-if="scope.row.shenhezt === '100'" :key="'b' + scope.$index"
                                    :type="config.shenhezt['100'].color" size="mini" disabled>
                                    审核
                                </el-button>
                                <el-button v-else-if="['101', '104'].includes(scope.row.shenhezt)"
                                    :key="'c' + scope.$index" type="primary" size="mini"
                                    @click="handleAudit(scope.row)">
                                    审核
                                </el-button>
                                <el-button v-else-if="['102', '103', '111'].includes(scope.row.shenhezt)"
                                    :key="'d' + scope.$index" size="mini" @click="handleView(scope.row)">
                                    查看
                                </el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </div>
                <!-- 弹出框内容 -->
                <el-dialog title="审核" :visible.sync="dialogVisible" :modal-append-to-body="false" top="10vh"
                    width="760px">
                    <el-descriptions style="margin-top: -20px;margin-bottom: -20px;" :column="3"
                        :labelStyle="{ width: '135px' }" :contentStyle="{ minWidth: '90px' }" size="medium" border>
                        <el-descriptions-item label="断面名称" :span="3">{{
                            dialogData.dmmc
                            }}</el-descriptions-item>
                        <el-descriptions-item label="监测时间">{{ formatTimestamp(dialogData.jcsj)
                            }}</el-descriptions-item>
                        <el-descriptions-item label="水质目标">{{
                            dialogData.szmb
                            }}</el-descriptions-item>
                        <el-descriptions-item label="水质类别">{{
                            getType(dialogData.szlb)
                            }}</el-descriptions-item>
                        <template>
                            <el-descriptions-item v-for="item in jcjgArray" :label="item.label" :key="item.value">{{
                                dialogData[item.value]
                                }}</el-descriptions-item>
                        </template>
                        <el-descriptions-item label="监测报告" :span="3">
                            <div v-for="(item, index) in updateFile(dialogData.filename)" :key="index">
                                <el-link :href="item.url" target="_blank" :underline="false">{{
                                    index + 1 + "、" + item.name
                                    }}</el-link>
                            </div>
                        </el-descriptions-item>
                    </el-descriptions>
                    <!-- 按钮区域 -->
                    <div slot="footer" style="text-align: center;">
                        <el-button type="danger" v-if="['101', '104'].includes(dialogData.shenhezt)"
                            @click="confirmReject">
                            回退
                        </el-button>
                        <el-button type="primary" v-if="['101'].includes(dialogData.shenhezt)" @click="handleApprove">
                            审核通过
                        </el-button>
                    </div>
                </el-dialog>
            </div>
            <div class="bottom">
                <el-pagination :current-page="currentPage" background layout="total, prev, pager, next, jumper"
                    :total="totalItems" :page-size="pageSize" @current-change="handleCurrentChange"
                    hide-on-single-page />
            </div>
        </el-main>
    </div>
</template>

<script>
import config from "@/config/config.js";
import { GetPermission } from '@/utils/auth'
import moment from "moment";
export default {
    name: "DataAudit",
    data() {
        return {
            config,
            dialogVisible: false,
            tableheight: 300,
            queryForm: {
                keyword: "", // 查询关键字
                yearMonth: "", // 年月信息
                selectedStatus: 'all',
                xzqhcode: '',
            },
            tableData: [], // 数据
            dialogData: {}, //根据id拿到的数据
            newdata: [],
            paginatedData: [], // 当前页的数据
            currentPage: 1, // 当前页码
            pageSize: 10, // 每页显示的数据量
            totalItems: 0, // 总项目数
            selectedIds: [], // 存储选择的项目的 ID
            jcjgArray: [],
        };
    },
    created() {
        const height = window.innerHeight - 200;
        this.tableheight = height;
        this.jcjgArray = config.jcjgArray;
        this.queryForm.xzqhcode = GetPermission().areacode;
        this.queryForm.yearMonth = moment().format('YYYY-MM');
        this.fetchData();
    },
    methods: {
        handleSelectionChange(selection) {
            let data = selection.filter(item => item.shenhezt == '101');
            this.selectedIds = data.map((item) => item.dmszjcid);
        },
        fetchData() {
            let month = new Date(this.queryForm.yearMonth).getMonth() + 1;
            // 调用 user.js 中的 getData 方法
            this.$api
                .getNDmSzjcInfo(this.queryForm.xzqhcode, this.queryForm.yearMonth)
                .then((response) => {
                    console.log("拿到的数据", response);
                    let data = response.data.data;
                    if (![3, 6, 9, 12].includes(month)) {
                        data = data.filter(item => item.jianceshijian == '月');
                    }
                    this.tableData = data;
                    this.resetdata(this.tableData || []);
                })
                .catch((error) => {
                    // 处理错误
                    console.error(error);
                });
        },
        resetdata(data) {
            let newdata = [];
            if (this.queryForm.selectedStatus == 'all') {
                newdata = data;
            } else if (this.queryForm.selectedStatus == 'wtj') {
                newdata = data.filter(item => item.shenhezt == '00' || item.shenhezt == '100');
            } else if (this.queryForm.selectedStatus == 'shtg') {
                newdata = data.filter(item => item.shenhezt == '102' || item.shenhezt == '111');
            } else {
                newdata = data.filter(item => item.shenhezt == this.queryForm.selectedStatus);
            }
            this.currentPage = 1;
            this.newdata = newdata;
            this.paginateData(newdata);
        },
        onDateChange(val) {
            this.queryForm.keyword = '';
            this.queryForm.yearMonth = moment(val).format('YYYY-MM')
            this.fetchData();
        },
        handSelectState() {
            this.queryForm.keyword = '';
            this.resetdata(this.tableData);
        },
        handInput(val) {
            console.log(val);
            if (val) {
                let data = this.tableData.filter(item => item.dmmc.toLowerCase().indexOf(val.trim()) !== -1);
                this.resetdata(data);
            } else {
                this.resetdata(this.tableData);
            }
        },
        // 点击审核
        handleAudit(row) {
            this.$api.getNDmSzjcDataById(row.dmszjcid).then((response) => {
                console.log("id数据", response.data.data);
                this.dialogData = response.data.data;
                this.dialogData.szmb = row.szmb;
                this.dialogVisible = true;
            });
        },
        // 点击查看
        handleView(row) {
            this.$api.getNDmSzjcDataById(row.dmszjcid).then((response) => {
                console.log("id数据", response.data.data);
                this.dialogData = response.data.data;
                this.dialogData.szmb = row.szmb;
                this.dialogVisible = true;
            });
        },

        // 切换分页
        paginateData(data) {
            console.log(data);
            const start = (this.currentPage - 1) * this.pageSize;
            const end = start + this.pageSize;
            this.totalItems = data.length;
            this.paginatedData = data.slice(start, end);
        },

        handleCurrentChange(val) {
            // 当用户切换分页时触发
            this.currentPage = val;
            this.paginateData(this.newdata);
        },

        // 将时间戳转换为格式化的日期字符串
        formatTimestamp(timestamp) {
            return moment(timestamp).format('YYYY-MM');;
        },
        // 审核通过
        handleApprove() {
            this.$confirm('确定要提交审核？', "审核提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
            })
                .then(() => {
                    // 用户点击了确定按钮
                    // 在这里调用审核通过的接口，并传递相应的数据项 ID
                    const id = this.dialogData.id;
                    const shenhezt = '102';
                    this.$api
                        .shenheNDmSzjcData(id, shenhezt)
                        .then((response) => {
                            console.log("审核通过成功", response);

                            // 处理审核通过成功的逻辑
                            this.$message.success("提交审核成功");
                            console.log("关闭框");
                            this.dialogVisible = false; // 关闭弹出框
                            this.fetchData();
                        })
                        .catch((error) => {
                            // 处理审核通过失败的逻辑
                            console.error("审核通过失败", error);
                            // 可以在这里做一些提示或者其他处理
                        });
                })
                .catch(() => {
                    // 用户点击了取消按钮
                    // 在这里可以不做任何处理，或者做一些额外的操作
                });
        },
        // 审核未通过
        confirmReject() {
            this.$confirm('确定要回退？', "回退提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
            })
                .then(() => {
                    // 用户点击了确定按钮
                    // 在这里调用审核通过的接口，并传递相应的数据项 ID
                    const id = this.dialogData.id;
                    const shenhezt = '103';
                    this.$api
                        .shenheNDmSzjcData(id, shenhezt)
                        .then((response) => {
                            console.log("回退成功", response);

                            // 处理审核通过成功的逻辑
                            this.$message.success("回退成功");
                            this.dialogVisible = false; // 关闭弹出框
                            this.fetchData();
                        })
                        .catch((error) => {
                            // 处理审核通过失败的逻辑
                            console.error("回退失败", error);
                            // 可以在这里做一些提示或者其他处理
                        });
                })
                .catch(() => {
                    // 用户点击了取消按钮
                    // 在这里可以不做任何处理，或者做一些额外的操作
                });
        },
        // 一键审核
        handleOneKeyAudit() {
            // if (this.selectedIds.length == 0) {
            //     this.$message('请选择可审核的数据！');
            //     return;
            // }
            this.$confirm(`一键审核数据通过，确定吗？`, "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "info",
            })
                .then(() => {
                    // 用户点击了确定按钮
                    // 在这里调用审核通过的接口，并传递相应的数据项 ID
                    // 假设 dialogData 中包含数据项的 ID
                    const shenhezt = '102';
                    this.dataAudit(shenhezt);
                })
                .catch(() => {
                    // 用户点击了取消按钮
                    // 在这里可以不做任何处理，或者做一些额外的操作
                });
        },
        // 一键回退
        handleOneKeyRollback() {
            // if (this.selectedIds.length == 0) {
            //     this.$message('请选择可审核的数据！');
            //     return;
            // }
            this.$confirm(`一键审核数据回退，确定吗？`, "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
            })
                .then(() => {
                    // 用户点击了确定按钮
                    // 在这里调用审核通过的接口，并传递相应的数据项 ID
                    // 假设 dialogData 中包含数据项的 ID
                    const shenhezt = '103';
                    this.dataAudit(shenhezt);
                })
                .catch(() => {
                    // 用户点击了取消按钮
                    // 在这里可以不做任何处理，或者做一些额外的操作
                });
        },
        dataAudit(shenhezt) {
            // console.log("id", this.selectedIds); // 假设 dialogData 中包含数据项的 ID
            let xzqhcode = this.queryForm.xzqhcode;
            let jcsj = this.queryForm.yearMonth;
            this.$api
                .batshztNDmSzjcData(xzqhcode, jcsj, shenhezt) // 假设调用的接口名为 oneKeyAudit
                .then((response) => {
                    // 处理一键审核成功的逻辑
                    console.log("批量审核返回的数据", response);
                    if (response.data.code == 0) {
                        this.$message.success(response.data.data);
                        this.fetchData(); // 刷新数据
                    } else {
                        this.$message.error("一键审核失败！");
                    }
                })
                .catch((error) => {
                    // 处理一键审核失败的逻辑
                    console.error("一键审核失败", error);
                    this.$message.error("一键审核失败");
                });
        },
        updateFile(str) {
            let filelist = str ? str.split(',').map(item => ({ name: item, url: process.env.VUE_APP_URL_URL + item })) : [];
            return filelist;
        },
        getType(sz) {
            if (sz == '' || sz == null) {
                return '未监测';
            } else if (sz == 0) {
                return '断流';
            } else {
                return config.typeArray.find(item => item.value == sz).label;
            }
        },
        handleDataExport() {
            this.$api
                .exportNDmSzjcInfo(this.queryForm.xzqhcode, this.queryForm.yearMonth)
                .then((response) => {
                    // 处理数据导出成功的逻辑
                    console.log("数据导出", response);
                    let url = process.env.VUE_APP_URL_URL + response.data.data;
                    window.open(url);
                })
                .catch((error) => {
                    // 处理数据导出失败的逻辑
                    this.$message.error("数据导出失败");
                });
        }
    },
};
</script>

<style scoped>
.el-main {
    color: #333;
    box-sizing: border-box;
}

.top {
    background-color: rgb(232, 232, 232);
    border-radius: 2px;
    padding-left: 20px;
    padding-top: 8px;
    padding-bottom: 7px;
    overflow: hidden;
}

.center {
    /* height: 400px; */
}

.el-form-item {
    margin-bottom: 2px;
    vertical-align: top;
    margin-right: 16px;
}

.bottom {
    text-align: right;
}

.file-upload {
    margin-right: 20px;
    /* 调整按钮之间的间距 */
}

.file-upload input {
    display: none;
}

/* 添加样式来美化文件选择按钮 */
.file-upload {
    display: inline-block;
    cursor: pointer;
    padding: 10px 20px;
    background-color: #3498db;
    color: #fff;
    border-radius: 5px;
}

.dialog-content {
    display: flex;
    /* flex-direction: column; */
    /* align-items: center; */
    justify-content: center;
    height: 100%;
}

.el-dialog__body {
    padding-top: 0;
}
</style>